package com.rtsapp.server.gamelog.client;


import com.rtsapp.server.gamelog.client.tail.LogDir;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户端配置
 */
public class LogConfig {

    private static final Logger LOG = LoggerFactory.getLogger(LogConfig.class);


    private final String serverIp;
    private final int serverPort;
    private final List<LogDir> dirList;

    public LogConfig(String serverIp, int serverPort, List<LogDir> dirList) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.dirList = dirList;
    }

    public static LogConfig parse(String fileName) throws Exception {

        Document dom = new SAXReader().read(new File(fileName));

        if (dom == null) {
            return null;
        }


        Element root = dom.getRootElement();

        //IP, port
        Element serverRoot = root.element("server");
        String ip = serverRoot.attributeValue("ip");
        int port = Integer.parseInt(serverRoot.attributeValue("port"));

        //所有日志目录
        List<LogDir> dirList = new ArrayList<>();
        Element logRoot = root.element("logs");
        List logElements = logRoot.elements("log");
        for (Object logObj : logElements) {
            if (logObj instanceof Element) {
                Element logElement = (Element) logObj;

                String gameId = logElement.attributeValue("gameId");
                String areaId = logElement.attributeValue("areaId");
                String serverId = logElement.attributeValue("serverId");
                String dir = logElement.attributeValue("dir");

                if (gameId == null || areaId == null || serverId == null || dir == null) {
                    LOG.error("非法配置: gameId={},areaId={},serverId={},dir={}", gameId, areaId, serverId, dir);
                    return null;
                }

                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    LOG.error("日志目录不存在: dir={}", dir);
                    return null;
                }

                if (!dirFile.isDirectory()) {
                    LOG.error("日志目录不是目录: dir={}", dir);
                    return null;
                }

                LogDir logDir = new LogDir(dirFile, gameId, areaId, serverId);
                dirList.add(logDir);
            }
        }

        LogConfig config = new LogConfig(ip, port, dirList);
        return config;
    }

    public String getServerIp() {
        return serverIp;
    }

    public int getServerPort() {
        return serverPort;
    }

    public List<LogDir> getDirList() {
        return dirList;
    }

}
